#!/bin/bash

URL=$1
i=0
END1=m3u8
END2=ts
URI_38=${URL}.${END1}

# 计数器
Counter() {
    counter_file="counter.txt"
	
    if [ ! -f "$counter_file" ]; then
    	echo 0 > "$counter_file"
    fi
    current_value=$(cat "$counter_file")
    new_value=$((current_value + 1))
    echo $new_value > "$counter_file"
    echo "Current value: $new_value"
}

# 下载并解析.m3u8文件
Download_m3u8() {
    echo "Downloading .m3u8 file..."
    wget -O file.m3u8 $URI_38  > /dev/null 2>&1
    echo "Counting .ts segments..."
    count=$(grep -c '.ts' file.m3u8)
}

# 更新进度条(以文件个数为单位)
update_progress() {
    local progress=$((current_file * 100 / count))
    printf "\r[%-50s] %d%%" "$(printf '%*s' $((progress * 50 / 100)) | tr ' ' '#')" $progress
}

# 循环下载.ts文件
Download_ts() {
    current_file=0
	
    echo -e "总计: $(( count - 1 ))"
    for (( i=0; i<$count; i++ )); do
      URI_ST=${URL}${i}.${END2}
      mkdir -p ${new_value}
      echo -e "Downloading ${i}.ts"
      wget -P /root/${new_value} $URI_ST  > /dev/null 2>&1
      ((current_file++))
      update_progress
    done
    echo
}

# 合并片段
Merged_fragment() {
    input_dir="/root/${new_value}"
    output_file="${new_value}.mp4"
    
    if ! command -v ffmpeg &> /dev/null
    then
        echo "ffmpeg could not be found. Please install it first."
        exit 1
    fi
    echo "Merging .ts files into a single video file..."
    find "$input_dir" -type f -name "*.ts" | sort -V | xargs -I {} sh -c 'echo file {} >> /tmp/playlist.txt'
    ffmpeg -f concat -safe 0 -i /tmp/playlist.txt -c copy "$output_file"
    rm /tmp/playlist.txt
    echo "Video file merged successfully: $output_file"
}

# 上传文件
Upload_file() {
    sz $output_file
}

# 清理文件
Clean_file() {
    rm -rf ${input_dir}/* $output_file file.m3u8 ${new_value}
}

# 主函数: 下载m3u8+解析+下载ts片段+合并片段+上传mp4+清理文件
main() {
    Counter &&\
	Download_m3u8 &&\
	Download_ts &&\
	Merged_fragment &&\
	Upload_file  &&\
	Clean_file
}

# 调用函数
main
